<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
// class Light {
//   constructor() {
//     // 设置当前状态
//     this.currState = FSM.off;
//     this.button = null;
//   }
//   init() {
//     let button =  document.createElement('button');
//     button.innerHTML = '已关灯';
//     this.button = () => {
//       // 把请求委托给FSM状态机
//       this.currState.buttonWasPressed.call(this)
//     }
//   }
// }
// let FSM = {
//   off: {
//     buttonWasPressed() {
//       console.log('关灯');
//       this.button.innerHTML = '下一次按我是开灯';
//       this.currState = FSM.on;
//     }
//   },
//   on: {
//     buttonWasPressed() {
//       console.log('开灯');
//       this.button.innerHTML = '下一次按我是关灯';
//       this.currState = FSM.off;
//     }
//   }
// }
// let light = new Light()
// light.init()

let delegate = function(client, delegation) {
  return {
    buttonWasPressed() {
      // 将客户的操作委托给delegation对象
      return delegation.buttonWasPressed.apply(client, arguments);
    }
  }
}
let FSM = {
  off: {
    buttonWasPressed() {
      console.log('关灯');
      this.button.innerHTML = '下一次按我是开灯';
      this.currState = this.onState;
    }
  },
  on: {
    buttonWasPressed() {
      console.log('开灯');
      this.button.innerHTML = '下一次按我是关灯';
      this.currState = this.offState;
    }
  }
}
class Light {
  constructor() {
    this.offState = delegate(this, FSM.off);
    this.onState = delegate(this, FSM.on);
    this.currState = this.offState;
    this.button = null;
  }
  init() {
    let button =  document.createElement('button');
    button.innerHTML = '已关灯';
    this.button = () => {
      // 把请求委托给FSM状态机
      this.currState.buttonWasPressed()
    }
  }
}
let light = new Light()
light.init()
</script>
</body>
</html>